﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DWF.Studio.Share.Log
{
    public class LogHelperLogMsg
    {
        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="projectname"></param>
        /// <param name="fileName"></param>
        /// <param name="contents"></param>
        /// <example>LogMsg("Sequence1","main","Begin DebugScript [2021/6/21 14:50:38]")
        /// 运行结果为：[exe Folder]\logs\2021-06-18\Flowchart1_main.log
        /// 日志文件添加行：Begin DebugScript [2021/6/21 14:50:38]
        /// </example>
        [SecuritySafeCritical]
        public void LogMsg(string projectname, string fileName, string contents, string fileNameExtend = "")
        {
            LogMsg(projectname, fileName, contents, Encoding.UTF8, fileNameExtend);
        }
        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="projectname"></param>
        /// <param name="fileName"></param>
        /// <param name="contents"></param>
        /// <param name="encoding"></param>
        /// <param name="directoryName">默认"logs"</param>
        [SecuritySafeCritical]
        public void LogMsg(string projectname, string fileName, string contents, Encoding encoding, string fileNameExtend = "", string directoryName = "logs")
        {
            string path = System.IO.Path.Combine(
                AppContext.BaseDirectory
                , directoryName
                , DateTime.Now.ToString("yyyy-MM-dd")
                , projectname + "_" + fileName + fileNameExtend + ".log"
                );
            InternalAppendAllLines(path, contents, encoding);
        }
        private void InternalAppendAllLines(string path, string contents, Encoding encoding)
        {
            try
            {
                //设置读写锁为写入模式独占资源，其他写入请求需要等待本次写入结束之后才能继续写入
                if (!Directory.Exists(Path.GetDirectoryName(path)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                }

                var logContentBytes = encoding.GetBytes(contents + Environment.NewLine);
                //设置了文件共享模式为允许随后写入
                using (FileStream logFile =
                    new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
                {
                    logFile.Seek(0, SeekOrigin.End);
                    logFile.Write(logContentBytes, 0, logContentBytes.Length);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
            finally
            {
            }
        }
    }
}
